# @Time    :2025/4/16 23:36
"""
使用多线程编写一个程序，模拟多个用户同时访问一个共享资源（如一个银行账户）的场景。定义一个BankAccount类，包含以下功能：
__init__方法，初始化账户余额为 0。
deposit方法，用于存款，接受一个参数amount表示存款金额。
withdraw方法，用于取款，接受一个参数amount表示取款金额，如果余额不足则提示 “Insufficient funds”。
使用多线程模拟多个用户同时进行存款和取款操作，注意处理线程安全问题。
"""
import threading


class BankAccount:
    def __init__(self):
        self.balance = 0
        self.lock = threading.Lock()

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit amount must be positive")
        with self.lock:
            self.balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal amount must be positive")
        with self.lock:
            if self.balance < amount:
                print("Insufficient funds")
            else:
                self.balance -= amount


def user_operation(account, operation, amount):
    if operation == "deposit":
        account.deposit(amount)
    elif operation == "withdraw":
        account.withdraw(amount)


account = BankAccount()
threads = []
operations = [("deposit", 100), ("withdraw", 50), ("deposit", 200), ("withdraw", 150)]
for operation, amount in operations:
    t = threading.Thread(target=user_operation, args=(account, operation, amount))
    threads.append(t)
    t.start()
for t in threads:
    t.join()
print(f"Final balance: {account.balance}")

# 在这个程序中，通过threading.Lock()来处理线程安全问题。在deposit和withdraw方法中使用with self.lock:语句，确保在同一时刻只有一个线程可以访问和修改账户余额，避免了数据竞争导致的错误结果
